package com.sy.filter;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CorsFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        //只能解决不需要携带凭证时候的跨域问题
        //res.setHeader("Access-Control-Allow-Origin", "*");


        // 不使用*，自动适配跨域域名，避免携带Cookie时失效
        String origin = req.getHeader("Origin");
        if (StringUtils.isNotBlank(origin)) {
            res.setHeader("Access-Control-Allow-Origin",origin);
        }


        // 自适应所有自定义头
        String headers = req.getHeader("Access-Control-Request-Headers");
        if(StringUtils.isNotBlank(headers)) {
            res.setHeader("Access-Control-Allow-Headers", headers);
            res.setHeader("Access-Control-Expose-Headers", headers);
        }

        // 允许跨域的请求方法类型
        res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT,PATCH");
        // 预检命令（OPTIONS）缓存时间，单位：秒
        res.setHeader("Access-Control-Max-Age", "3600");
        // 明确许可客户端发送Cookie，不允许删除字段即可
        res.setHeader("Access-Control-Allow-Credentials", "true");


        //要解决携带凭证时的跨域问题
//        res.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
//        res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT,PATCH");
//        res.setHeader("Access-Control-Max-Age", "0");
//        res.setHeader("Access-Control-Allow-Headers", "*");
//        res.setHeader("Access-Control-Allow-Credentials", "true");
//        res.setHeader("XDomainRequestAllowed", "1");

        chain.doFilter(req, res);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }


    @Override
    public void destroy() {

    }
}
